import React, {useEffect, useState} from 'react';
import {Table, Button, Modal, Form, Space, message, Input as AntInput} from 'antd';
import SpecialtyModal from "./component/SpecialtyModal.jsx";
import {
    addSpecialtyInfo,
    batchDeleteSpecialtyInfo,
    deleteSpecialtyInfo,
    getSpecialtyInfo,
    updateSpecialtyInfo
} from "../../api/specialty.js";
const SpecialtyPage = () => {
    const [form] = Form.useForm();
    const [data, setData] = useState([]);

    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingRecord, setEditingRecord] = useState(null);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [searchKeyword, setSearchKeyword] = useState('');
    const [loading,setLoading] = useState(false);

    const selectedRecords = data.filter(item => selectedRowKeys.includes(item.id));

    useEffect(() => {
        fetchSpecialtyInfo();
    }, []);
    const fetchSpecialtyInfo = async () => {
        setLoading(true);
        try {
            const res = await getSpecialtyInfo(null);
            setData(res.data);
        } catch (error) {
            message.error('获取专业列表失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };


    // ========== 表格配置 ==========
    const rowSelection = {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys) => {
            setSelectedRowKeys(selectedRowKeys);
        },
    };

    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, record, index) => index + 1,
        },
        {
            title: '所属学院名称',
            dataIndex: 'academyName',
            align: 'center',
            key: 'academyName'
        },
        {
            title: '专业名称',
            dataIndex: 'specialtyName',
            align: 'center',
            key: 'specialtyName'
        },
        {
            title: '专业代码',
            dataIndex: 'specialtyCode',
            align: 'center',
            key: 'specialtyCode'
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render: (_, record) => (
                <Space size="middle">
                    <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
                    <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
                </Space>
            )
        }
    ];

    // ========== 操作方法 ==========
    const handleDelete = (id) => {
        Modal.confirm({
            title: '确认删除该专业信息？',
            onOk: () => {
                deleteSpecialty({
                    specialtyId: id
                })
            }
        });
    };

    const handleBatchDelete = () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请至少选择一条记录');
            return;
        }

        Modal.confirm({
            title: '确认删除选中的专业信息？',
            onOk: () => {
                batchDeleteSpecialty({
                    ids: selectedRowKeys
                });
            }
        });
    };

    const handleEdit = (record) => {
        setEditingRecord(record);
        form.setFieldsValue(record);
        setIsModalVisible(true);
    };

    const handleAdd = () => {
        setEditingRecord(null);
        form.resetFields();
        setIsModalVisible(true);
    };

    const handleOk = (values) => {
        if (editingRecord) {
            updateSpecialty({
                id: editingRecord.id,
                academyId: values.academyId,
                specialtyName: values.specialtyName,
                specialtyCode: values.specialtyCode
            });
        } else {
            addSpecialty({
                academyId: values.academyId,
                specialtyName: values.specialtyName,
                specialtyCode: values.specialtyCode
            });
        }
        setIsModalVisible(false);
        form.resetFields();
    };

    const addSpecialty = async (data) => {
        try {
            const res = await addSpecialtyInfo(data);
            if (res.code === 200) {
                message.success("新增成功")
                fetchSpecialtyInfo();
            }
        } catch (error) {
            message.error('新增专业失败');
            console.error(error);
        }
    }
    const updateSpecialty = async (data) => {
        try {
            const res = await updateSpecialtyInfo(data);
            if (res.code === 200) {
                message.success("修改成功")
                fetchSpecialtyInfo();
            }
        } catch (error) {
            message.error('修改专业信息失败');
            console.error(error);
        }
    }
    const deleteSpecialty = async (data) => {
        try {
            const res = await deleteSpecialtyInfo(data);
            if (res.code === 200) {
                message.success("删除成功")
                fetchSpecialtyInfo();
            }
        } catch (error) {
            message.error('删除专业信息失败');
            console.error(error);
        }
    }
    const batchDeleteSpecialty = async (data) => {
        try {
            const res = await batchDeleteSpecialtyInfo(data);
            if (res.code === 200) {
                message.success("批量删除成功")
                fetchSpecialtyInfo();
                setSelectedRowKeys([]);
            }
        } catch (error) {
            message.error('批量删除专业信息失败');
            console.error(error);
        }
    }

    const handleCancel = () => {
        setIsModalVisible(false);
        form.resetFields();
    };

    const handleInputChange = (e) => {
        if (e.target.value === '') {
            fetchSpecialtyInfo();
        }
        setSearchKeyword(e.target.value);
    };

    const handleSearch = async () => {
        if (!searchKeyword.trim()) {
            message.warning('请输入搜索内容');
            return;
        }

        setLoading(true);
        try {
            const res = await getSpecialtyInfo(searchKeyword);
            setData(res.data);
        } catch (error) {
            message.error('获取专业列表失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div style={{padding: 14}}>
            <div style={{
                marginBottom: 16,
                display: 'flex',
                justifyContent: 'space-between',
                flexWrap: 'wrap',
                gap: 8
            }}>
                <Space>
                    <Button type="primary" onClick={handleAdd}>新增专业</Button>
                    <Button danger disabled={selectedRowKeys.length === 0} onClick={handleBatchDelete}>
                        批量删除
                    </Button>
                </Space>

                <Space>
                    <AntInput.Search
                        placeholder="请输入专业名称"
                        value={searchKeyword}
                        onChange={handleInputChange}
                        onSearch={handleSearch}
                        style={{width: 250}}
                        allowClear
                    />
                </Space>
            </div>

            <Table
                rowKey="id"
                dataSource={data}
                columns={columns}
                rowSelection={rowSelection}
                loading={loading}
            />

            <SpecialtyModal
                visible={isModalVisible}
                onOk={handleOk}
                onCancel={handleCancel}
                editingRecord={editingRecord}
            />
        </div>
    );
};

export default SpecialtyPage;